package com.csun.cmny.provider.service.impl;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.base.enums.ErrorCodeEnum;
import com.csun.cmny.core.support.BaseService;
import com.csun.cmny.provider.dao.OmcShiftLogMapper;
import com.csun.cmny.provider.exceptions.OmcBizException;
import com.csun.cmny.provider.model.domain.OmcNursingRoomBind;
import com.csun.cmny.provider.model.domain.OmcSchedul;
import com.csun.cmny.provider.model.domain.OmcShiftLog;
import com.csun.cmny.provider.model.domain.OmcShifts;
import com.csun.cmny.provider.model.dto.DeviceAlertDto;
import com.csun.cmny.provider.model.vo.DeviceAlertReqVo;
import com.csun.cmny.provider.model.vo.RpcRoleVo;
import com.csun.cmny.provider.pojo.Bed;
import com.csun.cmny.provider.service.*;
import com.csun.cmny.provider.utils.DateUtil;
import com.csun.cmny.provider.utils.MenuTimeUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class OmcShiftLogServiceImpl extends BaseService<OmcShiftLog> implements OmcShiftLogService {

    @Resource
    private OmcShiftLogMapper omcShiftLogMapper;

    @Resource
    private OmcRoomAssignmentService omcRoomAssignmentService;

    @Resource
    private UacRpcService uacRpcService;

    @Resource
    private OmcGroupService omcGroupService;

    @Resource
    private OmcScheduleService omcScheduleService;

    @Resource
    private DmcRpcService dmcRpcService;

    @Resource
    private BedService bedService;

    @Resource
    private OmcNursingRoomBindService omcNursingRoomBindService;

    @Resource
    private OmcShiftsService omcShiftsService;

    @Override
    public List<OmcShifts> queryShiftsList(OmcShiftLog omcShiftLog, LoginAuthDto loginAuthDto) {

        //获取护工组id
        int nursingGroupId = getNursingGroupId(omcShiftLog.getNursingGroupId(),loginAuthDto);

        //获取查询日期
        String date = omcShiftLog.getDate();

        //创建查询对象
        OmcSchedul omcSchedulQuery = new OmcSchedul();
        //转换时间格式
        String week = MenuTimeUtil.getDays(date).get(1) + MenuTimeUtil.getDays(date).get(0);
        omcSchedulQuery.setWeek(Integer.parseInt(week));
        omcSchedulQuery.setNursingGroupId(nursingGroupId);

        //查询交班项
        List<OmcShifts> omcShiftsList = omcRoomAssignmentService.queryShiftsList(omcSchedulQuery);
        //查询排班计划
        List<OmcSchedul> omcSchedulList = omcScheduleService.select(omcSchedulQuery);

        if(omcSchedulList != null && omcSchedulList.size() > 0){

            //将排班计划中的护工姓名放入每个交班项
            for(OmcSchedul omcSchedul : omcSchedulList){

                //周一
                if(date.equals(omcSchedul.getMonDate())){
                    for(OmcShifts omcShifts : omcShiftsList){
                        if(String.valueOf(omcSchedul.getShiftsId()).equals(String.valueOf(omcShifts.getId()))){
                            omcShifts.setUserIdString(omcSchedul.getMonUserId());
                            omcShifts.setUserNameString(omcSchedul.getMonRealName());
                        }
                    }
                }
                //周二
                if(date.equals(omcSchedul.getTueDate())){
                    for(OmcShifts omcShifts : omcShiftsList){
                        if(String.valueOf(omcSchedul.getShiftsId()).equals(String.valueOf(omcShifts.getId()))){
                            omcShifts.setUserIdString(omcSchedul.getTueUserId());
                            omcShifts.setUserNameString(omcSchedul.getTueRealName());
                        }
                    }
                }
                if(date.equals(omcSchedul.getWedDate())){
                    for(OmcShifts omcShifts : omcShiftsList){
                        if(String.valueOf(omcSchedul.getShiftsId()).equals(String.valueOf(omcShifts.getId()))){
                            omcShifts.setUserIdString(omcSchedul.getWedUserId());
                            omcShifts.setUserNameString(omcSchedul.getWedRealName());
                        }
                    }
                }
                if(date.equals(omcSchedul.getThuDate())){
                    for(OmcShifts omcShifts : omcShiftsList){
                        if(String.valueOf(omcSchedul.getShiftsId()).equals(String.valueOf(omcShifts.getId()))){
                            omcShifts.setUserIdString(omcSchedul.getThuUserId());
                            omcShifts.setUserNameString(omcSchedul.getThuRealName());
                        }
                    }
                }
                if(date.equals(omcSchedul.getFriDate())){
                    for(OmcShifts omcShifts : omcShiftsList){
                        if(String.valueOf(omcSchedul.getShiftsId()).equals(String.valueOf(omcShifts.getId()))){
                            omcShifts.setUserIdString(omcSchedul.getFriUserId());
                            omcShifts.setUserNameString(omcSchedul.getFriRealName());
                        }
                    }
                }
                if(date.equals(omcSchedul.getSatDate())){
                    for(OmcShifts omcShifts : omcShiftsList){
                        if(String.valueOf(omcSchedul.getShiftsId()).equals(String.valueOf(omcShifts.getId()))){
                            omcShifts.setUserIdString(omcSchedul.getSatUserId());
                            omcShifts.setUserNameString(omcSchedul.getSatRealName());
                        }
                    }
                }
                if(date.equals(omcSchedul.getSunDate())){
                    for(OmcShifts omcShifts : omcShiftsList){
                        if(String.valueOf(omcSchedul.getShiftsId()).equals(String.valueOf(omcShifts.getId()))){
                            omcShifts.setUserIdString(omcSchedul.getSunUserId());
                            omcShifts.setUserNameString(omcSchedul.getSunRealName());
                        }
                    }
                }
            }
        }
        return omcShiftsList;
    }

    @Override
    public List<OmcShiftLog> selectByDate(OmcShiftLog omcShiftLog, LoginAuthDto loginAuthDto) {

        //获取护工组id
        int nursingGroupId = getNursingGroupId(omcShiftLog.getNursingGroupId(),loginAuthDto);

        omcShiftLog.setNursingGroupId(nursingGroupId);
        List<OmcShiftLog> shiftlogList = omcShiftLogMapper.selectByDate(omcShiftLog);

        //判断该排班计划是否已经通过
        //1.查询排班计划
        OmcSchedul schedulQuery = new OmcSchedul();
        String week = MenuTimeUtil.getDays(omcShiftLog.getDate()).get(1) + MenuTimeUtil.getDays(omcShiftLog.getDate()).get(0);
        schedulQuery.setWeek(Integer.valueOf(week));
        schedulQuery.setNursingGroupId(omcShiftLog.getNursingGroupId());
        List<OmcSchedul> listSchedul = omcScheduleService.queryScheduleList(schedulQuery, loginAuthDto);

        //2.当无查询结果时
        if (listSchedul.size() <= 0 || listSchedul == null) {
            throw new OmcBizException(ErrorCodeEnum.OMC10036001);
            //3.有查询结果时，判断排班计划的审批状态  0- 未审批 1-审批未通过 2-审批通过
        } else if(listSchedul.get(0).getStatus() == 0 || listSchedul.get(0).getStatus() == 1){
            throw new OmcBizException(ErrorCodeEnum.OMC10036002);
        }

        //将护工字符串处理成集合
        for(int i=0;i<=shiftlogList.size()-1;i++){
            List<Long> list = new ArrayList<Long>();
            if(shiftlogList.get(i).getUser() == null || shiftlogList.get(i).getUser().length() == 0){
                shiftlogList.get(i).setUserList(list);
                continue;
            }
            String arr[] = shiftlogList.get(i).getUser().split("-");

            //护工集合
            for(int j=0;j<=arr.length-1;j++){
                list.add(Long.valueOf(arr[j]));
            }
            //处理护工姓名集合
            List<String> realNameList = Lists.newArrayList();
            if (StringUtils.isNotEmpty(shiftlogList.get(i).getRealName())) {
                realNameList = Arrays.asList(shiftlogList.get(i).getRealName().split("-"));
            }
            shiftlogList.get(i).setRealNameList(realNameList);
            shiftlogList.get(i).setUserList(list);
        }
        return shiftlogList;
    }

    /*
     * 添加或修改排班计划
     * */
    @Override
    public int batchAddShiftLog(List<OmcShiftLog> omcShiftLogList, LoginAuthDto loginAuthDto) {

        int nursingGroupId = getNursingGroupId(omcShiftLogList.get(0).getNursingGroupId(),loginAuthDto);

        //放入操作者信息
        for(OmcShiftLog item : omcShiftLogList){
            item.setNursingGroupId(nursingGroupId);
            item.setUpdateInfo(loginAuthDto);
        }
        int ret = batchSave(omcShiftLogList);
        return ret;
    }

    @Override
    public int batchUpdateShiftLog(List<OmcShiftLog> omcShiftLogList, LoginAuthDto loginAuthDto) {

        //校验护工组id
        int nursingGroupId = getNursingGroupId(omcShiftLogList.get(0).getNursingGroupId(),loginAuthDto);

        //统计更新条数
        int count = 0;

        //放入操作者信息
        for(OmcShiftLog item : omcShiftLogList){
            item.setNursingGroupId(nursingGroupId);
            item.setUpdateInfo(loginAuthDto);
            //校验id
            if(item.getId() == null || item.getId() == 0){
                throw new OmcBizException(ErrorCodeEnum.OMC10036004);
            }
            //更新
            int ret = omcShiftLogMapper.updateByPrimaryKeySelective(item);
            if(ret <1){
                return ret;
            }
            count+=ret;
        }
        return count;
    }

    @Override
    public List<DeviceAlertReqVo> selectMainExc(OmcShiftLog omcShiftLog, LoginAuthDto loginAuthDto) {

        int nursingGroupId = getNursingGroupId(omcShiftLog.getNursingGroupId(),loginAuthDto);

        //创建查询对象
        DeviceAlertReqVo deviceAlertReqVo = new DeviceAlertReqVo();

        //查询老人id集合
        List<Integer> oldmanIdList = omcShiftLogMapper.queryOldmanIdList(nursingGroupId);

        //放入查询对象
        deviceAlertReqVo.setOldmanIdList(oldmanIdList);

        //生成时间查询条件
        String strArr[] = omcShiftLog.getShiftTime().split("-");
        String time1 = "";
        String time2 = "";

        //判断当前班次是否跨天，如果跨天
        String strTime1[] = strArr[0].split(":");
        String strTime2[] = strArr[1].split(":");
        time1 = omcShiftLog.getDate() + " " + strArr[0];
        if (Integer.parseInt(strTime1[0]) > Integer.parseInt(strTime2[0])) {
            //跨天
            String date = DateUtil.getTomorrow(omcShiftLog.getDate());
            time2 = date + " " + strArr[1];
        }else {
            //不跨天
            time2 = omcShiftLog.getDate() + " " + strArr[1];
        }
        //放入查询对象
        deviceAlertReqVo.setStartTime(time1);
        deviceAlertReqVo.setEndTime(time2);

        if(oldmanIdList == null || oldmanIdList.size() < 1){
            throw new OmcBizException(ErrorCodeEnum.OMC10036003);
        }

        //查询报警信息
        List<DeviceAlertReqVo> deviceAlertReqVoList = dmcRpcService.queryDeviceAlertByOldIdAndDate(deviceAlertReqVo);

        return deviceAlertReqVoList;
    }

    @Override
    public Integer syncAlertMsgToShiftLog(DeviceAlertDto dto) {

        //现在时刻
        Date now = new Date();
        log.info("=========【报警时间】" + now + "【报警类型】" + dto.getAlertType() + "【报警信息】" + dto.getAlertInfo() + "=========================");

        //根据老人Id查询护工组
        Bed bedQuery = new Bed();
        bedQuery.setOldmanId(dto.getOldmanId());
        bedQuery = bedService.selectByBed(bedQuery);
        if (bedQuery == null) {
            throw new OmcBizException(ErrorCodeEnum.OMC10037038);
        }

        OmcNursingRoomBind nursingRoomBind = new OmcNursingRoomBind();
        nursingRoomBind.setRoomId(bedQuery.getRoomId().longValue());
        nursingRoomBind = omcNursingRoomBindService.selectOne(nursingRoomBind);
        if (nursingRoomBind == null) {
           throw new OmcBizException(ErrorCodeEnum.OMC10031206);
        }

        //获取当日日期
        String todayDate = DateUtil.getDate_dtShort();
        OmcShiftLog shiftLogQuery = new OmcShiftLog();

        //查询当日交班日志
        shiftLogQuery.setNursingGroupId(nursingRoomBind.getNursingGroupId().intValue());
        shiftLogQuery.setDate(todayDate);
        List<OmcShiftLog> shiftLogList = select(shiftLogQuery);

        //如果当日排班日志未生成
        if (shiftLogList.size() < 1) {
            //查询当日排班计划
            OmcSchedul schedulQuery = new OmcSchedul();
            schedulQuery.setNursingGroupId(nursingRoomBind.getNursingGroupId().intValue());
            String week = MenuTimeUtil.getDays(todayDate).get(1) + MenuTimeUtil.getDays(todayDate).get(0);
            schedulQuery.setWeek(Integer.parseInt(week));
            List<OmcSchedul> schedulList = omcScheduleService.select(schedulQuery);

            if (schedulList.size() < 1) {
                throw new OmcBizException(ErrorCodeEnum.OMC10036001);
            } else {
                //如果护理日志未生成,查询交班项,生成护理日志
                OmcShifts shiftsQuery = new OmcShifts();
                shiftsQuery.setPlanid(schedulList.get(0).getPlanId().longValue());
                List<OmcShifts> shiftsList = omcShiftsService.select(shiftsQuery);

                for (OmcShifts shifts : shiftsList) {
                    //设置交班日志数据
                    OmcShiftLog shiftLog = new OmcShiftLog();
                    shiftLog.setDate(todayDate);
                    shiftLog.setNursingGroupId(nursingRoomBind.getNursingGroupId().intValue());
                    shiftLog.setShiftsId(shifts.getId());

                    //生成时间查询条件
                    String strArr[] = shifts.getTime().split("-");
                    String time1 = "";
                    String time2 = "";

                    //判断当前班次是否跨天，如果跨天
                    String strTime1[] = strArr[0].split(":");
                    String strTime2[] = strArr[1].split(":");
                    time1 = todayDate + " " + strArr[0];
                    if (Integer.parseInt(strTime1[0]) > Integer.parseInt(strTime2[0])) {
                        //跨天
                        String date = DateUtil.getTomorrow(todayDate);
                        time2 = date + " " + strArr[1];
                    }else {
                        //不跨天
                        time2 = todayDate + " " + strArr[1];
                    }

                    Date startTime = DateUtil.getDateLong(time1);
                    Date endTime = DateUtil.getDateLong(time2);

                    //放入报警信息
                    if (now.before(endTime) && now.after(startTime)) {
                        log.info("========== 【写入报警信息的交班项时间】" + shifts.getTime() + "==============");
                        shiftLog.setAlertInfo(dto.getAlertInfo());
                    }

                    //放入该日的护工姓名
                    for (OmcSchedul schedul : schedulList) {
                        if (shifts.getId().toString().equals(schedul.getShiftsId().toString())) {
                            if(schedul.getMonDate().equals(todayDate)){
                                shiftLog.setUser(schedul.getMonUserId());
                                shiftLog.setRealName(schedul.getMonRealName());
                            } else if (schedul.getTueDate().equals(todayDate)) {
                                shiftLog.setUser(schedul.getTueDate());
                                shiftLog.setRealName(schedul.getTueRealName());
                            } else if (schedul.getWedDate().equals(todayDate)) {
                                shiftLog.setUser(schedul.getWedDate());
                                shiftLog.setRealName(schedul.getWedRealName());
                            } else if (schedul.getThuDate().equals(todayDate)) {
                                shiftLog.setUser(schedul.getThuUserId());
                                shiftLog.setRealName(schedul.getThuRealName());
                            } else if (schedul.getFriDate().equals(todayDate)) {
                                shiftLog.setUser(schedul.getFriUserId());
                                shiftLog.setRealName(schedul.getFriRealName());
                            } else if (schedul.getSatDate().equals(todayDate)) {
                                shiftLog.setUser(schedul.getSatDate());
                                shiftLog.setRealName(schedul.getSatRealName());
                            } else if (schedul.getSunDate().equals(todayDate)) {
                                shiftLog.setUser(schedul.getSunDate());
                                shiftLog.setRealName(schedul.getSunRealName());
                            }
                        }
                    }
                    shiftLogList.add(shiftLog);
                }
                return batchSave(shiftLogList);
            }
        } else {
            for (OmcShiftLog shiftLog : shiftLogList) {
                //生成时间查询条件
                OmcShifts shifts = omcShiftsService.selectByKey(shiftLog.getShiftsId());
                String strArr[] = shifts.getTime().split("-");
                String time1 = "";
                String time2 = "";

                //判断当前班次是否跨天，如果跨天
                String strTime1[] = strArr[0].split(":");
                String strTime2[] = strArr[1].split(":");
                time1 = todayDate + " " + strArr[0];
                if (Integer.parseInt(strTime1[0]) > Integer.parseInt(strTime2[0])) {
                    //跨天
                    String date = DateUtil.getTomorrow(todayDate);
                    time2 = date + " " + strArr[1];
                }else {
                    //不跨天
                    time2 = todayDate + " " + strArr[1];
                }

                Date startTime = DateUtil.getDateLong(time1);
                Date endTime = DateUtil.getDateLong(time2);

                //放入报警信息
                if (now.before(endTime) && now.after(startTime)) {
                    if (shiftLog.getAlertInfo() == null) {
                        log.info("========== 【写入报警信息的交班项时间】" + shifts.getTime() + "==============");
                        shiftLog.setAlertInfo(dto.getAlertInfo());
                    } else {
                        log.info("========== 【写入报警信息的交班项时间】" + shifts.getTime() + "==============");
                        shiftLog.setAlertInfo(shiftLog.getAlertInfo().concat(";"+dto.getAlertInfo()));
                    }
                    return update(shiftLog);
                }
            }
        }
        return 0;
    }

    public int getNursingGroupId(Integer omcNurisngGroupId,LoginAuthDto loginAuthDto){

        //查询用户身份
        List<RpcRoleVo> rpcRoleVos = uacRpcService.queryRoleListByUserId(loginAuthDto.getUserId());

        //定义班组id
        Integer nursingGroupId = 0;

        for(RpcRoleVo vo : rpcRoleVos){
            //1.身份为护工时，班组id为护工所在的班组id
            if(vo.getRoleCode().equals("nursing")){
                nursingGroupId = omcGroupService.selectNuringGroupIdByUserId(loginAuthDto.getUserId()).intValue();
                //2.身份为服务部长时，班组id为服务部长指定的id
            }else {
                nursingGroupId = omcNurisngGroupId;
            }
        }
        if( nursingGroupId == null || nursingGroupId == 0 ){
            throw new OmcBizException(ErrorCodeEnum.OMC10035006);
        }
        return nursingGroupId;
    }
}
